package com.lw.leetcode.dp.b;

/**
 * Created with IntelliJ IDEA.
 * 1143. 最长公共子序列
 * 剑指 Offer II 095. 最长公共子序列
 *
 * @author liw
 * @version 1.0
 * @date 2021/9/3 16:50
 */
public class LongestCommonSubsequence {

    public static void main(String[] args) {
        LongestCommonSubsequence test = new LongestCommonSubsequence();

//        String a = "abcba";
//        String b = "abcbcba";


        String a ="abasdgrhjhdgytjhdsfac";
        String b = "rthsdgfhtrgsdfdryutrteuo";

        String c = "abasdgrhjthsdgytjfhdtrgsdfacdryutrteuo";
        System.out.println(a.length());
        System.out.println(b.length());
        System.out.println(c.length());

        int i = test.longestCommonSubsequence(a, b);
        System.out.println(i);

    }

    public int longestCommonSubsequence(String text1, String text2) {
        int a = text1.length();
        int b = text2.length();
        int[] dp = new int[b + 1];
        for (int i = 0; i < a; i++) {
            int item = 0;
            for (int j = 0; j < b; j++) {
                int v = dp[j + 1];
                dp[j + 1] = text1.charAt(i) == text2.charAt(j) ? item + 1 : Math.max(dp[j], dp[j + 1]);
                item = v;
            }
        }
        return dp[b];
    }

    public int longestCommonSubsequence2(String text1, String text2) {
        int a = text1.length();
        int b = text2.length();
        int[][] dp = new int[a + 1][b + 1];
        for (int i = 0; i < a; i++) {
            for (int j = 0; j < b; j++) {
                if (text1.charAt(i) == text2.charAt(j)) {
                    dp[i + 1][j + 1] = dp[i][j] + 1;
                } else {
                    dp[i + 1][j + 1] = Math.max(dp[i + 1][j], dp[i][j + 1]);
                }
            }
        }
        return dp[a][b];
    }

}
